//
//  XUIProgressSelectorView.m
//  etionUI
//
//  Created by WangJian on 14-12-19.
//  Copyright (c) 2014年 GuangZhouXuanWu. All rights reserved.
//

#import "XUIProgressSelectorView.h"

@implementation XUIProgressSelectorLayer

- (id)init
{
    self = [super init];
    if (self)
    {
        self.opaque = NO;
        
        self.backgroundColor = [UIColor redColor].CGColor;
//        [self displayIfNeeded];
    }
    return self;
}

//- (void)setProgress:(CGFloat)progress
//{
//    [self setProgress:progress animated:NO];
//}

- (void)setProgress:(CGFloat)progress animated:(BOOL)animated
{
    if (animated)
    {
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        animation.fromValue = [NSNumber numberWithFloat:_progress];
        animation.toValue = [NSNumber numberWithFloat:progress];
        animation.duration = 3;
        animation.removedOnCompletion = NO;
//        animation.fillMode = kCAFillModeForwards;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        
//        [self removeAllAnimations];
        [self addAnimation:animation forKey:nil];
        
        self.progress = progress;
    }
    else
    {
        _progress = progress;
        [self setNeedsDisplay];
    }
}

- (void)drawInContext:(CGContextRef)ctx
{
    CGContextSetStrokeColorWithColor(ctx, [UIColor flatRedColor].CGColor);
    CGContextSetFillColorWithColor(ctx, [UIColor flatRedColor].CGColor);
    
    CGContextSetLineWidth(ctx, 2);
    CGContextAddEllipseInRect(ctx, CGRectInset(self.bounds, 1, 1));
    CGContextStrokePath(ctx);
    
    CGContextMoveToPoint(ctx, self.bounds.size.width/2, self.bounds.size.height/2);
    CGContextAddArc(ctx, self.bounds.size.width/2, self.bounds.size.height/2, self.bounds.size.width/2, M_PI_2*3, M_PI_2*3 + _progress*2*M_PI, 0);
    CGContextClosePath(ctx);
    CGContextFillPath(ctx);
}

@end

@implementation XUIProgressSelectorView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.selectorLayer = [[[XUIProgressSelectorLayer alloc] init] autorelease];
//        self.layer = self.selectorLayer;
        self.selectorLayer.frame = self.bounds;
        [self.layer addSublayer:self.selectorLayer];
        
        self.selectorLayer.progress = 0.3;
    }
    return self;
}

-(void)dealloc
{
    [_selectorLayer release_mm];
    superdealloc_mm;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
